package pub.elephants.socket.netty.client;

import com.sun.xml.internal.ws.api.streaming.XMLStreamReaderFactory;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import pub.elephants.serializable.ElephantsSerializable;

/**
 * Created by IntelliJ IDEA.
 * User: kui.zhang
 * Date: 2017/8/1
 * Time: 9:26
 * To change this template use File | Settings | File Templates.
 */
public class NettyClientPoolFactory extends BasePooledObjectFactory<NettyClientPoolProxy> {
    private String host;
    private int port;
    private ElephantsSerializable serializer;

    public NettyClientPoolFactory(String host, int port, ElephantsSerializable serializer) {
        this.host = host;
        this.port = port;
        this.serializer = serializer;
    }

    @Override
    public NettyClientPoolProxy create() throws Exception {
        NettyClientPoolProxy nettyClientPoolProxy = new NettyClientPoolProxy();
        nettyClientPoolProxy.createProxy(host, port, serializer);
        return nettyClientPoolProxy;
    }

    @Override
    public PooledObject<NettyClientPoolProxy> wrap(NettyClientPoolProxy nettyClientPoolProxy) {
        return new DefaultPooledObject<NettyClientPoolProxy>(nettyClientPoolProxy);
    }

    @Override
    public void destroyObject(PooledObject<NettyClientPoolProxy> p) throws Exception {
        if (p.getObject() != null)
            p.getObject().close();
    }

    @Override
    public boolean validateObject(PooledObject<NettyClientPoolProxy> p) {
        if (p.getObject() != null)
            return p.getObject().isValidate();
        return false;
    }


}
